﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using Microsoft.Build.Evaluation;

namespace CompletionData
{
    public class ReservedProperties
    {
        private static ReservedProperties instance;
        private IDictionary<string, string> propertiesCache;

        private ReservedProperties()
        {
        }

        public static ReservedProperties GetInstance()
        {
            if (instance == null)
                instance = new ReservedProperties();

            return instance;
        }

        public void Clear()
        {
            if (this.propertiesCache != null)
                this.propertiesCache.Clear();
        }

        public IDictionary<string, string> GetProperties()
        {
            IDictionary<string, string> result = new SortedDictionary<string, string>(propertiesCache);
            return propertiesCache;
        }

        public string GetProperty(string propertyName)
        {
            if (string.IsNullOrWhiteSpace(propertyName))
                throw new ArgumentNullException();

            if (this.propertiesCache == null)
                return null;
            if (!this.propertiesCache.ContainsKey(propertyName))
                return null;
            return propertiesCache[propertyName];
        }

        public void CreateData(string fileName)
        {
            if (string.IsNullOrWhiteSpace(fileName))
                throw new ArgumentNullException();

            propertiesCache = new SortedDictionary<string, string>();

            Project proj = new Project();
            proj.ProjectCollection.UnloadAllProjects();
            proj.FullPath = fileName;
            ICollection<ProjectProperty> props = proj.Properties;
            foreach (ProjectProperty prop in props)
            {
                propertiesCache.Add(prop.Name, prop.EvaluatedValue);
            }
            propertiesCache.Add("MSBuildProjectFile", Path.GetFileName(fileName));
            propertiesCache.Add("MSBuildProjectName", Path.GetFileNameWithoutExtension(fileName));
            propertiesCache.Add("MSBuildProjectExtension", Path.GetExtension(fileName));
            propertiesCache.Add("MSBuildProjectFullPath", fileName);
            string rootName = Path.GetPathRoot(fileName);
            string fileDir = Path.GetDirectoryName(fileName);
            string fileDirNoRoot = fileDir.Replace(rootName, string.Empty);
            propertiesCache.Add("MSBuildProjectDirectoryNoRoot", fileDirNoRoot);
            propertiesCache["MSBuildProjectDirectory"] = fileDir;

        }

    }
}
